package mspbots.teams.client.core.data.planners;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.log4j.Log4j2;
import mspbots.teams.client.core.AbstractToolsUtil;
import mspbots.teams.client.oauth.TokenState;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.Map;

/**
 * mspbots.data.teams.core.groups.GroupsService
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/6/3
 */
@Log4j2
@Service
public class PlannersServiceImpl extends AbstractToolsUtil {

    public Flux<JsonNode> getGroups(Long tenantId) {
        return this.dataClient.get()
                .uri(uriBuilder -> uriBuilder.path("/groups/{tenantId}/find").build(tenantId))
                .retrieve()
                .bodyToFlux(JsonNode.class);
    }

    public Flux<JsonNode> find(Long tenantId) {
        return this.getGroups(tenantId)
                .flatMap(resultNode -> this.get(resultNode.get("otherId").textValue()))
                .contextWrite(ctx -> ctx.put("tokenState", TokenState.withDefault(tenantId)));
    }

    private Flux<JsonNode> get(String groupId) {
        return this.teamsClient.fetch("/v1.0/groups/{groupId}/planner/plans",
                null, Map.of("groupId", groupId))
                .onErrorResume(err -> {
                    log.debug("Get groupId: {}, err msg: {}", groupId, err.getMessage());
                    return Mono.empty();
                })
                .flatMap(jsonNode -> Flux.fromIterable(jsonNode.withArray("value")));
    }


}
